
package com.rt.schedulenew.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.rt.schedulebase.dto.ExamApplyDto;
import com.rt.schedulebase.dto.ExamApplyItemDto;
import com.rt.schedulebase.dto.ExamPatientLockDto;
import com.rt.schedulebase.entity.ExamApply;
import com.rt.schedulebase.entity.ExamPatientLock;
import com.rt.schedulebase.mapper.ExamApplyItemMapper;
import com.rt.schedulebase.mapper.ExamApplyMapper;
import com.rt.schedulebase.mapper.ExamPatientLockMapper;
import com.rt.schedulenew.api.ICommonService;
import com.rt.schedulenew.api.IExamPatientLockService;
import com.rt.schedulenew.utils.base.CommonUtil;
import com.rt.schedulenew.utils.global.JsonResult;
import com.rt.schedulenew.utils.global.JsonResultUtil;
import com.rt.schedulenew.utils.global.PageVO;
import com.rt.schedulenew.utils.util.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

@Service
public class ExamPatientLockServiceImpl extends ServiceImpl<ExamPatientLockMapper, ExamPatientLock> implements IExamPatientLockService {
    @Autowired
    private ExamApplyMapper examApplyMapper;
    @Autowired
    private ExamApplyItemMapper examApplyItemMapper;
    @Autowired
    private ICommonService commonServiceImpl;
    @Autowired
    IExamPatientLockService examPatientLockService;

    @Override
    public int addPatientLock(ExamPatientLock examPatientLock) {
        examPatientLock.setLockStatus("1");
        examPatientLock.setLockDate(DateUtil.getCurrDateStr());
        examPatientLock.setLockTime(DateUtil.getCurrentTime());
        examPatientLock.setLockCount(1);
        ExamPatientLock lock = baseMapper.selectById(examPatientLock.getSickId());
        if (lock != null) {
            examPatientLock.setLockCount(lock.getLockCount() + examPatientLock.getLockCount());
            return baseMapper.updateById(examPatientLock);
        }
        return baseMapper.insert(examPatientLock);
    }

    @Override
    public JsonResult unLockPatient(ExamPatientLockDto dto) {
        if (!StringUtils.isNotBlank((dto.getSickId()))) {
            return JsonResultUtil.failure("病人标识号不能为空！");
        }
        StringBuilder errMsgs = new StringBuilder();
        List<String> sickIdList = CommonUtil.split2List(dto.getSickId());
        for (String sickId : sickIdList) {
            QueryWrapper<ExamPatientLock> qw = new QueryWrapper<>();
            qw.eq("SICK_ID", sickId);
            ExamPatientLock lock = new ExamPatientLock();
            lock.setLockStatus("0");
            int updateResult = baseMapper.update(lock, qw);
            if (updateResult == -1) {
                errMsgs.append("，" + sickId);
            }
        }
        if (StringUtils.isNotBlank((errMsgs.toString()))) {
            return JsonResultUtil.failure("[" + errMsgs.substring(1) + "]病人解锁失败！");
        }
        return JsonResultUtil.success("解锁成功！");
    }

    /***
     * 查询患者黑名单
     * @param dto
     * @return
     */
    @Override
    public List<ExamPatientLockDto> selectList(ExamPatientLockDto dto) {
        QueryWrapper<ExamPatientLock> qw = new QueryWrapper<>();
        Map<String, Object> map = new HashMap<>();
        if (StringUtils.isNotBlank(dto.getName())) {
            map.put("NAME", dto.getName());
        }
        if (StringUtils.isNotBlank(dto.getIcCard())) {
            map.put("IC_CARD", dto.getIcCard());
        }
        qw.allEq(map, false).eq("LOCK_STATUS", "1");

        // 如果院区不为空
        if (StringUtils.isNotBlank(dto.getHospitalCode())) {
            QueryWrapper<ExamApply> examApplyQw = new QueryWrapper<>();
            examApplyQw.eq("HOSPITAL_CODE", dto.getHospitalCode());
            examApplyQw.select("SICK_ID");
            List<ExamApply> examApplyList = examApplyMapper.selectList(examApplyQw);
            if (examApplyList != null && !examApplyList.isEmpty()) {
                List<String> sickList = new ArrayList<>();
                for (ExamApply examApply : examApplyList) {
                    sickList.add(examApply.getSickId());
                }
                qw.in("SICK_ID", sickList);
            }
        }
        if (StringUtils.isNotBlank(dto.getStartDate())) {
            qw.ge("LOCK_DATE", dto.getStartDate());
        }
        if (StringUtils.isNotBlank(dto.getEndDate())) {
            qw.le("LOCK_DATE", dto.getEndDate());
        }
        List<ExamPatientLock> list = baseMapper.selectList(qw);
        List<ExamPatientLockDto> examPatientLockList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            for (ExamPatientLock lock : list) {
                ExamPatientLockDto examPatientLockDto = new ExamPatientLockDto();
                BeanUtils.copyProperties(lock, examPatientLockDto);
                ExamApplyDto ea = new ExamApplyDto();
                ea.setSickId(lock.getSickId());
                List<ExamApplyDto> examApplyList2 = examApplyMapper.getExamScheduleForBreakPromise(ea);
                if (examApplyList2 != null && !examApplyList2.isEmpty()) {
                    Map<String, ExamApplyDto> theExamApplyMap = new HashMap<>();
                    for (ExamApplyDto examApplyDto : examApplyList2) {
                        if (examApplyDto.getSigninOvertimeCnt() != null && examApplyDto.getSigninOvertimeCnt() > 0) {
                            String key = examApplyDto.getScheduledId() + examApplyDto.getApplyNo();
                            if (!theExamApplyMap.containsKey(key)) {
                                examApplyDto.setItemNoStr(String.valueOf(examApplyDto.getItemNo()));
                            } else {
                                ExamApplyDto applyInfo = theExamApplyMap.get(key);
                                examApplyDto.setItemNoStr(applyInfo.getItemNoStr() + "," + examApplyDto.getItemNo());
                            }
                            theExamApplyMap.put(key, examApplyDto);
                        }
                    }
                    List<ExamApplyDto> examApplys = new ArrayList<ExamApplyDto>();
                    Object[] keys = theExamApplyMap.keySet().toArray();
                    Arrays.sort(keys);
                    for (Object keyItem : keys) {
                        ExamApplyDto eaDto = theExamApplyMap.get(keyItem);
                        ExamApplyItemDto examApplyItemDto = new ExamApplyItemDto();
                        examApplyItemDto.setApplyNo(eaDto.getApplyNo());
                        examApplyItemDto.setItemNos(CommonUtil.split2List(eaDto.getItemNoStr()));
                        List<ExamApplyItemDto> items = examApplyItemMapper.getList(examApplyItemDto);
                        commonServiceImpl.handItemCode(items, eaDto.getExamSubClass());
                        StringBuffer itemNames = new StringBuffer();
                        for (ExamApplyItemDto eai : items) {
                            int amount = (eai.getAmount() != null) ? eai.getAmount() : 1;
                            itemNames.append("；" + eai.getItemName());
                            if (amount > 1) {
                                itemNames.append(" 00d7" + amount);
                            }
                        }
                        eaDto.setItemNameStr((itemNames.length() > 0) ? itemNames.substring(1) : "");
                        examApplys.add(eaDto);
                    }
                    examPatientLockDto.setExamApplys(examApplys);
                }
                examPatientLockList.add(examPatientLockDto);
            }
        }
        return examPatientLockList;
    }

    @Override
    public JsonResult getBlackList(ExamPatientLockDto dto) {
        Page<?> page = PageHelper.startPage(dto.getPageNo(), dto.getPageSize());
        List<ExamPatientLockDto> list = examPatientLockService.selectList(dto);
        PageVO pageVO = new PageVO();
        pageVO.setPageNo(dto.getPageNo());
        pageVO.setPageSize(dto.getPageSize());
        pageVO.setTotal(page.getTotal());
        pageVO.setPages(page.getPages());
        return JsonResultUtil.success("成功", list, pageVO);
    }
}
